package civicinity.ist.psu.edu.events;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import civicinity.ist.psu.edu.CivicinityLogin;
import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.adapter.CivicinityRSSCalAdapter;
import civicinity.ist.psu.edu.adapter.CivicinityShareListViewAdapter;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.rssfeed.RSSFeed;
import civicinity.ist.psu.edu.rssfeed.RSSFeedHandler;
import civicinity.ist.psu.edu.rssfeed.RSSItem;
import civicinity.ist.psu.edu.utils.DownloadHandler;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.component.VEvent;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class CivicinityCalFeed extends Activity implements OnItemClickListener{

	private ProgressBar mSpinner;
	private TextView mLoadingTxt;
	private ArrayList<RSSCalInfo> mArr = new ArrayList<RSSCalInfo>();
	
	private int mEventID;
	private String mEventURL;
	private String mEventTitle;
	private boolean mEventActive;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.civicinity_event_ical);

	    mSpinner = (ProgressBar) findViewById(R.id.spinner);
	    mLoadingTxt = (TextView) findViewById(R.id.loading_text);
	    
	    Intent gIntent = getIntent();
	    mEventID = gIntent.getExtras().getInt("event_id");
	    mEventURL = gIntent.getExtras().getString("event_feed_url");
	    mEventTitle = gIntent.getExtras().getString("event_title");
	    
	    //mEventActive = gIntent.getExtras().getBoolean("event_active");
	    
	    if(mEventTitle.equals("Daily Events by CDT")) {
	    	new loadCalendarRSSEvents().execute();
	    }
	    else {
	    	new loadCalendarEvents().execute();
	    }
	    
	    // TODO: to make this smarter, make some algorithm to update the data once a day or something.
	    // getting the data all the time takes some time and lower the user experiences..
	    
	}
	
	class loadCalendarRSSEvents extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			getRSSFeed();
			return null;
		}
		
		@Override
		protected void onPostExecute(Void unused) {
			
			mSpinner.setVisibility(View.GONE);
			mLoadingTxt.setVisibility(View.GONE);
			
			ListView vList = (ListView) findViewById(R.id.itemlist);
			CivicinityRSSCalAdapter adapter = new CivicinityRSSCalAdapter(CivicinityCalFeed.this, R.layout.cal_rss_item, mArr);
			vList.setAdapter(adapter);
			vList.setOnItemClickListener(CivicinityCalFeed.this);
			vList.setSelection(0);
		}
		
	}
	
	private void getRSSFeed() {
		RSSFeedHandler feedHandler = new RSSFeedHandler();
    	RSSFeed feed = feedHandler.getFeed(Constants.CDT_EVENT_CALENDER_RSS);
    	
    	try {
			for(int j = 0 ; j < feed.getAllItems().size() ; j++) {
				RSSCalInfo cInfo = new RSSCalInfo();
				// title
				cInfo.eTitle = feed.getItem(j).getTitle().trim();

				// description
				cInfo.eDescription = feed.getItem(j).getDescription().trim();
				
				// split start date
				String[] sDate = feed.getItem(j).getStartDate().trim().split(" ");
				//cInfo.eStartDate = sDate[0] + " " + sDate[1];
				cInfo.eStartDate = "";
				
				for(int k = 0 ; k < sDate.length ; k++) {
					if(k == 2) {
						break;
					}
					
					if(!sDate[k].equals(null)) {
						String sDateSub = "";
						if(k == 0) {
							sDateSub = sDate[k].substring(5, 10);
						}
						if(k == 1) {
							sDateSub = sDate[k].substring(0, 5);
						}
						cInfo.eStartDate += sDateSub + " ";
					}
				}
				
				
				// split end date, so far just show the start time.
				cInfo.eEndDate = "";
				if(!feed.getItem(j).getEndDate().equals(null)) {
					String[] eDate = feed.getItem(j).getEndDate().trim().split(" ");
					for(int k = 0 ; k < eDate.length ; k++) {
						if(k == 2) {
							break;
						}
						cInfo.eEndDate += eDate[k] + " ";
					}
				}
				else {
					cInfo.eEndDate = "";
				}
				
				// location
				cInfo.eLocation = feed.getItem(j).getLatitude() + "," + feed.getItem(j).getLongitude();
    		
        		mArr.add(cInfo);
         		
        		arraySorting();
    		}
		}
		catch(Exception e) {
			//Toast.makeText(RSSReader.this, "Errors while fetching the news", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
	
	private void arraySorting() {
 		
 		Comparator<RSSCalInfo> compare = new Comparator<RSSCalInfo>() {

 			@Override
    			public int compare(RSSCalInfo obj1, RSSCalInfo obj2) {
    				// TODO Auto-generated method stub
    				return String.valueOf(obj1.eStartDate).compareToIgnoreCase(String.valueOf(obj2.eStartDate));
				}
 		};
		
    	Collections.sort(mArr, compare);
	}
	
	class loadCalendarEvents extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Void doInBackground(Void... unused) {
			// TODO Auto-generated method stub
 		    try {

 		    	// get the data from the server first
 		    	DownloadHandler dHandler = new DownloadHandler();
 		    	if(dHandler.downloadFiles(mEventURL, mEventID)) {
 		    		
 		    		if(Looper.myLooper() == null) {
 		    			Looper.prepare();
 		    		}
 		    		
 		    		Log.i("K", "file downloaded, start parsing the file");
 		    		
 		    		CalendarBuilder builder = new CalendarBuilder();
 			        Calendar calendar = null;
 			        
 			        File readFile = new File(Constants.CIVICINITY_FILE_PATH + mEventID + ".ics");
 			        
 			        if(!readFile.exists()) {
 			        	Toast.makeText(CivicinityCalFeed.this, "File doesn't exist", Toast.LENGTH_SHORT).show();
 			        	finish();
 			        }
 			        
 			        FileInputStream is = new FileInputStream(readFile);
 			        calendar = builder.build(is);
 			        //calendar = builder.build(getResources().openRawResource(R.drawable.art_festival));
 			        	
 			        StringBuilder b = new StringBuilder();
 			        b.append(calendar.getProperty("X-WR-CALNAME").getValue());
 			        for (Object event : calendar.getComponents(Component.VEVENT)) {
 			        	if (((VEvent) event).getSummary() != null) {
 			        		RSSCalInfo cInfo = new RSSCalInfo();
 			        		cInfo.eTitle = ((VEvent) event).getSummary().getValue();
 			        		cInfo.eDescription = ((VEvent) event).getDescription().getValue();
 			        		
 			        		Log.i("K", "startDate: " + ((VEvent) event).getStartDate().getValue());
 			        		Log.i("K", "endDate: " + ((VEvent) event).getEndDate().getValue());
 			        		
 			        		String startDate = ((VEvent) event).getStartDate().getValue();
 			        		String startYear = startDate.substring(0, 4);
 			        		String startMonth = startDate.substring(4, 6);
 			        		String startDay = startDate.substring(6, 8);
 			        		String startHour = startDate.substring(9, 11);
 			        		String startMin = startDate.substring(11, 13);
 			        		
 			        		cInfo.eStartDate = startMonth + "-" + startDay + " " + startHour + ":" + startMin;
 			        		
 			        		String endDate = ((VEvent) event).getEndDate().getValue();
 			        		String endYear = endDate.substring(0, 4);
 			        		String endMonth = endDate.substring(4, 6);
 			        		String endDay = endDate.substring(6, 8);
 			        		String endHour = endDate.substring(9, 11);
 			        		String endMin = endDate.substring(11, 13);
 			        		
 			        		cInfo.eEndDate = endMonth + "-" + endDay + " " + endHour + ":" + endMin;
 			        		if(((VEvent) event).getLocation() != null) {
 			        			cInfo.eLocation =  ((VEvent) event).getLocation().getValue();
 			        		}
 			        		
 			        		//if(!((VEvent) event).getGeographicPos().getLatitude().equals(null)) {
 			        		//	cInfo.eLatitude = ((VEvent) event).getGeographicPos().getLatitude().doubleValue();
 				        	//	cInfo.eLongitude = ((VEvent) event).getGeographicPos().getLongitude().doubleValue();
 			        		//}
 			        		
 			        		
 			        		mArr.add(cInfo);
 		
 			        		arraySorting();
	 			           		
 			           		b.append("\n\n");
 			           		b.append(((VEvent) event).getSummary().getValue());
 			           		b.append(": ");
 			           		b.append(((VEvent) event).getStartDate().getDate());
 			        	}
 			        }
 		    	}
 		    	else {
 		    		mSpinner.setVisibility(View.GONE);
 			    	mLoadingTxt.setText("No Events are scheduled at this moment.");
 		    	}
		        
				//tv.setText("Hello, " + b.toString());
			} catch (Exception e) {
				Log.e("test", "unexpected error", e);
			}	
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void unused) {
			
			mSpinner.setVisibility(View.GONE);
			mLoadingTxt.setVisibility(View.GONE);
			
			ListView vList = (ListView) findViewById(R.id.itemlist);
			CivicinityRSSCalAdapter adapter = new CivicinityRSSCalAdapter(CivicinityCalFeed.this, R.layout.cal_rss_item, mArr);
			vList.setAdapter(adapter);
			vList.setOnItemClickListener(CivicinityCalFeed.this);
			vList.setSelection(0);
		}
	}
	
	public class RSSCalInfo implements Cloneable{
		public String eTitle;
		public String eDescription;
		public String eStartDate;
		public String eEndDate;
		public String eLocation;
		
		public RSSCalInfo clone() throws CloneNotSupportedException {
			RSSCalInfo fItem = (RSSCalInfo)super.clone();
			
			return fItem;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(CivicinityCalFeed.this, CivicinityCalFeedDetail.class);
		
		intent.putExtra("eTitle", mArr.get(position).eTitle);
		intent.putExtra("eDescription", mArr.get(position).eDescription);
		intent.putExtra("eStartDate", mArr.get(position).eStartDate);
		intent.putExtra("eEndDate", mArr.get(position).eEndDate);
		intent.putExtra("eLocation", mArr.get(position).eLocation);
		
		startActivity(intent);
	}
}


/**
for (Iterator i = calendar.getComponents().iterator(); i.hasNext();) {
Component component = (Component) i.next();
System.out.println("Component [" + component.getName() + "]");

for (Iterator j = component.getProperties().iterator(); j.hasNext();) {
    Property property = (Property) j.next();
    System.out.println("Property [" + property.getName() + ", " + property.getValue() + "]");
}
}
*/